import { PublishBase } from "./PublishBase";
import { join } from "path";
import * as rimraf from 'rimraf';
import { mkdirSync, writeFileSync, existsSync, unlinkSync, createWriteStream } from "fs";
import { paserHtml, mergeJs2, getFacebookIndexHtml } from "./PaserHtmlUtil";
import { createDirSync, cpDir } from "../utils/FileUtil";
import * as archiver from 'archiver';

export class FaceBookPublish extends PublishBase {
    get projDir(){return "facebook";}
    createProject() {
        let tplPath = this.mTempProjPath
        let verPath = join(this._publishVo.toPath, this._version);
        this.log('创建项目目录:' + verPath);
        if (existsSync(verPath)) {
            this.doPack();
            return;
        }
        rimraf(verPath, (err2) => {
            if (err2) {
                console.warn(`清理目录${verPath}出错`);
                return;
            }

            mkdirSync(join(this._publishVo.toPath, this._version));
            let toPath = join(this._publishVo.toPath, this._version);
            cpDir(tplPath, toPath, () => {
                this.log('项目生成完毕');
            });
        });
    }

    doPack() {
        // 解析html文件
        let htmlObj = paserHtml(this._publishVo.fromPath);

        this.log('开始修改config.json');
        // 写入config
        let crtProjPath = join(this._publishVo.toPath, this._version);
        writeFileSync(join(crtProjPath, this.getConfigName()), this._publishVo.config);

        this.log('开始合并js代码');
        // console.log('html', getFacebookIndexHtml(htmlObj.js, htmlObj.html));
        // return;
        // 合并js列表
        let htmlJs = ['libs.js', 'code.js'];
        // let jsPath = join(this._publishVo.fromPath, 'js');
        // let tojsPath = join(crtProjPath, 'js');
        // let libPath = join(this._publishVo.fromPath, 'libs');
        // let tolibPath = join(crtProjPath, 'libs');
        // cpDir(jsPath, tojsPath, () => {
        //     cpDir(libPath, tolibPath, () => {
        mergeJs2(htmlObj.js, this._publishVo.fromPath, crtProjPath, 'code.js', (outNames: string[]) => {
            let indexStr = getFacebookIndexHtml(htmlJs, htmlObj.html);
            writeFileSync(join(crtProjPath, 'index.html'), indexStr);
            // 拷贝素材
            cpDir(join(this._publishVo.fromPath, 'res'), join(crtProjPath, 'res'), () => {
                this.log('素材拷贝完毕');
                let zipPath = join(this._publishVo.toPath, `facebook_pack${this._version}.zip`);
                if (existsSync(zipPath)) {
                    unlinkSync(zipPath);
                }
                this.zipPack(crtProjPath, this._publishVo.toPath, `facebook_pack${this._version}.zip`);
                this.packOver();
            });
        });

        // },false, { file: ['\S*?\.map'] });
    }

    zipPack(fromDir: string, toDir: string, zipName: string) {
        this.log('开始将项目打包成zip文件');
        if (!existsSync(toDir)) {
            createDirSync(toDir);
        }
        let output = createWriteStream(join(toDir, zipName));
        let arch = archiver('zip', { zlib: { level: 9 } });
        output.on('close', () => {
            console.log(arch.pointer() + ' total bytes');
            console.log('archiver has been finalized and the output file descriptor has closed.');
        });
        output.on('end', () => {
            console.log('Data has been drained');
        });
        arch.on('warning', (err: any) => {
            if (err.code === 'ENOENT') {
                // log warning
            } else {
                // throw error
                throw err;
            }
        });
        arch.on('error', (err: any) => {
            throw err;
        });
        arch.pipe(output);
        arch.directory(fromDir, false);
        arch.finalize();
        this.log('打包zip完毕');
    }

}